/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Persistencia;

import Persistencia.exceptions.NonexistentEntityException;
import Persistencia.exceptions.PreexistingEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import motoressa.Zona;
import motoressa.Taller;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.transaction.UserTransaction;
import motoressa.Sucursal;

/**
 *
 * @author HP
 */
public class SucursalJpaController implements Serializable {

    public SucursalJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public SucursalJpaController() {
        emf=Persistence.createEntityManagerFactory("MotoresSAPU");
    }
    

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Sucursal sucursal) throws PreexistingEntityException, Exception {
        if (sucursal.getMisTalleres() == null) {
            sucursal.setMisTalleres(new ArrayList<Taller>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Zona miZona = sucursal.getMiZona();
            if (miZona != null) {
                miZona = em.getReference(miZona.getClass(), miZona.getCodigo());
                sucursal.setMiZona(miZona);
            }
            List<Taller> attachedMisTalleres = new ArrayList<Taller>();
            for (Taller misTalleresTallerToAttach : sucursal.getMisTalleres()) {
                misTalleresTallerToAttach = em.getReference(misTalleresTallerToAttach.getClass(), misTalleresTallerToAttach.getCodigo());
                attachedMisTalleres.add(misTalleresTallerToAttach);
            }
            sucursal.setMisTalleres(attachedMisTalleres);
            em.persist(sucursal);
            if (miZona != null) {
                Sucursal oldMiSucursalOfMiZona = miZona.getMiSucursal();
                if (oldMiSucursalOfMiZona != null) {
                    oldMiSucursalOfMiZona.setMiZona(null);
                    oldMiSucursalOfMiZona = em.merge(oldMiSucursalOfMiZona);
                }
                miZona.setMiSucursal(sucursal);
                miZona = em.merge(miZona);
            }
            for (Taller misTalleresTaller : sucursal.getMisTalleres()) {
                Sucursal oldMiSucursalOfMisTalleresTaller = misTalleresTaller.getMiSucursal();
                misTalleresTaller.setMiSucursal(sucursal);
                misTalleresTaller = em.merge(misTalleresTaller);
                if (oldMiSucursalOfMisTalleresTaller != null) {
                    oldMiSucursalOfMisTalleresTaller.getMisTalleres().remove(misTalleresTaller);
                    oldMiSucursalOfMisTalleresTaller = em.merge(oldMiSucursalOfMisTalleresTaller);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findSucursal(sucursal.getCodigo()) != null) {
                throw new PreexistingEntityException("Sucursal " + sucursal + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Sucursal sucursal) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sucursal persistentSucursal = em.find(Sucursal.class, sucursal.getCodigo());
            Zona miZonaOld = persistentSucursal.getMiZona();
            Zona miZonaNew = sucursal.getMiZona();
            List<Taller> misTalleresOld = persistentSucursal.getMisTalleres();
            List<Taller> misTalleresNew = sucursal.getMisTalleres();
            if (miZonaNew != null) {
                miZonaNew = em.getReference(miZonaNew.getClass(), miZonaNew.getCodigo());
                sucursal.setMiZona(miZonaNew);
            }
            List<Taller> attachedMisTalleresNew = new ArrayList<Taller>();
            for (Taller misTalleresNewTallerToAttach : misTalleresNew) {
                misTalleresNewTallerToAttach = em.getReference(misTalleresNewTallerToAttach.getClass(), misTalleresNewTallerToAttach.getCodigo());
                attachedMisTalleresNew.add(misTalleresNewTallerToAttach);
            }
            misTalleresNew = attachedMisTalleresNew;
            sucursal.setMisTalleres(misTalleresNew);
            sucursal = em.merge(sucursal);
            if (miZonaOld != null && !miZonaOld.equals(miZonaNew)) {
                miZonaOld.setMiSucursal(null);
                miZonaOld = em.merge(miZonaOld);
            }
            if (miZonaNew != null && !miZonaNew.equals(miZonaOld)) {
                Sucursal oldMiSucursalOfMiZona = miZonaNew.getMiSucursal();
                if (oldMiSucursalOfMiZona != null) {
                    oldMiSucursalOfMiZona.setMiZona(null);
                    oldMiSucursalOfMiZona = em.merge(oldMiSucursalOfMiZona);
                }
                miZonaNew.setMiSucursal(sucursal);
                miZonaNew = em.merge(miZonaNew);
            }
            for (Taller misTalleresOldTaller : misTalleresOld) {
                if (!misTalleresNew.contains(misTalleresOldTaller)) {
                    misTalleresOldTaller.setMiSucursal(null);
                    misTalleresOldTaller = em.merge(misTalleresOldTaller);
                }
            }
            for (Taller misTalleresNewTaller : misTalleresNew) {
                if (!misTalleresOld.contains(misTalleresNewTaller)) {
                    Sucursal oldMiSucursalOfMisTalleresNewTaller = misTalleresNewTaller.getMiSucursal();
                    misTalleresNewTaller.setMiSucursal(sucursal);
                    misTalleresNewTaller = em.merge(misTalleresNewTaller);
                    if (oldMiSucursalOfMisTalleresNewTaller != null && !oldMiSucursalOfMisTalleresNewTaller.equals(sucursal)) {
                        oldMiSucursalOfMisTalleresNewTaller.getMisTalleres().remove(misTalleresNewTaller);
                        oldMiSucursalOfMisTalleresNewTaller = em.merge(oldMiSucursalOfMisTalleresNewTaller);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                int id = sucursal.getCodigo();
                if (findSucursal(id) == null) {
                    throw new NonexistentEntityException("The sucursal with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(int id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Sucursal sucursal;
            try {
                sucursal = em.getReference(Sucursal.class, id);
                sucursal.getCodigo();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The sucursal with id " + id + " no longer exists.", enfe);
            }
            Zona miZona = sucursal.getMiZona();
            if (miZona != null) {
                miZona.setMiSucursal(null);
                miZona = em.merge(miZona);
            }
            List<Taller> misTalleres = sucursal.getMisTalleres();
            for (Taller misTalleresTaller : misTalleres) {
                misTalleresTaller.setMiSucursal(null);
                misTalleresTaller = em.merge(misTalleresTaller);
            }
            em.remove(sucursal);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Sucursal> findSucursalEntities() {
        return findSucursalEntities(true, -1, -1);
    }

    public List<Sucursal> findSucursalEntities(int maxResults, int firstResult) {
        return findSucursalEntities(false, maxResults, firstResult);
    }

    private List<Sucursal> findSucursalEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Sucursal as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Sucursal findSucursal(int id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Sucursal.class, id);
        } finally {
            em.close();
        }
    }

    public int getSucursalCount() {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select count(o) from Sucursal as o");
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
